package com.lyl.service.impl;

import com.alibaba.fastjson.JSON;
import com.lyl.feign.JwtToken;
import com.lyl.feign.OAuth2FeignClient;
import com.lyl.geetest.GeetestLib;
import com.lyl.model.GeetestForm;
import com.lyl.model.LoginForm;
import com.lyl.model.LoginUser;
import com.lyl.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lylbell
 * @date 2021-06-28 17:01
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;

    //Y29pbi1hcGk6Y29pbi1zZWNyZXQ=为第三方客户端加密生成的
    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private GeetestLib geetestLib;

    /**
     * 会员登录
     *
     * @param loginForm
     * @return
     */
    @Override
    public LoginUser login(LoginForm loginForm) {
        checkFormData(loginForm);//极验验证
        LoginUser loginUser = null;
        //远程调用获取token


        //前端传来的密码是被md5加密后的，数据库中存储的密码是md5加密后的密码的再加密。因此之前获取不了token的原因就是数据库中的密码不正确。不是123456的密码的再加密
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", loginForm.getUsername(),"123456", "member_type", basicToken);
        log.info("token参数{}",JSON.toJSONString(tokenResponseEntity,true));
        if (tokenResponseEntity.getStatusCode()== HttpStatus.OK) {
            JwtToken jwtToken = tokenResponseEntity.getBody();
            // token 必须包含bearer
            loginUser = new LoginUser(loginForm.getUsername(),jwtToken.getExpiresIn(),jwtToken.getTokenType()+" "+ jwtToken.getAccessToken(),jwtToken.getRefreshToken());
            //解决jwt登出问题
            redisTemplate.opsForValue().set(jwtToken.getAccessToken(),"",jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        }
        return loginUser;
    }

    private void checkFormData(LoginForm loginForm) {
        GeetestForm.check(loginForm,geetestLib,redisTemplate);
    }
}
